package com.taixu.apiorder.controller;

import java.util.Date;
import java.util.List;
import java.util.Arrays;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import com.taixu.apikey.domain.vo.ApiKeyVo;
import com.taixu.apikey.service.IApiKeyService;
import com.taixu.business.fegin.CallBackClient;
import com.taixu.business.vo.CallbackBody;
import com.taixu.business.vo.OrderInfo;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.taixu.common.annotation.RepeatSubmit;
import com.taixu.common.annotation.Log;
import com.taixu.common.core.controller.BaseController;
import com.taixu.common.core.domain.PageQuery;
import com.taixu.common.core.domain.R;
import com.taixu.common.core.validate.AddGroup;
import com.taixu.common.core.validate.EditGroup;
import com.taixu.common.enums.BusinessType;
import com.taixu.common.utils.poi.ExcelUtil;
import com.taixu.apiorder.domain.vo.ApiOrderVo;
import com.taixu.apiorder.domain.bo.ApiOrderBo;
import com.taixu.apiorder.service.IApiOrderService;
import com.taixu.common.core.page.TableDataInfo;

/**
 * 订单
 *
 * @author ximu
 * @date 2023-12-14
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/service/apiorder")
public class ApiOrderController extends BaseController {

    private final IApiOrderService iApiOrderService;

    private final IApiKeyService iApiKeyService;

    private final CallBackClient callBackClient;
    /**
     * 查询订单列表
     */
    @SaCheckPermission("service:apiorder:list")
    @GetMapping("/list")
    public TableDataInfo<ApiOrderVo> list(ApiOrderBo bo, PageQuery pageQuery) {
        TableDataInfo<ApiOrderVo> apiOrderVoTableDataInfo = iApiOrderService.queryPageList(bo, pageQuery);
        List<ApiOrderVo> apiOrderVos = iApiOrderService.queryListByEesc(pageQuery.getPageNum()-1, pageQuery.getPageSize());
        apiOrderVoTableDataInfo.setRows(apiOrderVos);
        return apiOrderVoTableDataInfo;
    }

    /**
     * 导出订单列表
     */
    @SaCheckPermission("service:apiorder:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ApiOrderBo bo, HttpServletResponse response) {
        List<ApiOrderVo> list = iApiOrderService.queryList(bo);
        ExcelUtil.exportExcel(list, "订单", ApiOrderVo.class, response);
    }

    /**
     * 获取订单详细信息
     *
     * @param orderId 主键
     */
    @SaCheckPermission("service:apiorder:query")
    @GetMapping("/{orderId}")
    public R<ApiOrderVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long orderId) {
        return R.ok(iApiOrderService.queryById(orderId));
    }

    /**
     * 新增订单
     */
    @SaCheckPermission("service:apiorder:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ApiOrderBo bo) {
        return toAjax(iApiOrderService.insertByBo(bo));
    }

    /**
     * 修改订单
     */
    @SaCheckPermission("service:apiorder:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ApiOrderBo bo) {


        //判断是否驳回状态
        if(bo.getResStatus() != 30){
            java.util.Date date = new Date();//获得当前时间
            bo.setStatus(40L);
            bo.setFinishTime(date);
            //无异常
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrder_id(bo.getOrderId());
            orderInfo.setOrder_no(bo.getOrderNo());
            orderInfo.setCph(bo.getCph());
            orderInfo.setVin(bo.getVin());
            orderInfo.setResult(bo.getResult());
            orderInfo.setStatus(bo.getStatus());
            orderInfo.setRes_status(bo.getResStatus());
            orderInfo.setPush_status(bo.getPushStatus());
            orderInfo.setCreate_time(bo.getFoundTime());
            orderInfo.setFinish_time(bo.getFinishTime());
            CallbackBody callbackBody = new CallbackBody();
            callbackBody.setOrderInfo(orderInfo);

            //查询地址
            ApiKeyVo apiKeyVo = iApiKeyService.queryByKey(bo.getBykey());

            String rs = callBackClient.helloForest(callbackBody,apiKeyVo.getPushaddress());
            if(rs.equals("OK")){
                bo.setPushStatus(10L);
            }
        }else {
            //有异常
            java.util.Date date = new Date();//获得当前时间
            bo.setResStatus(30L);
            bo.setPushStatus(30L);
            bo.setStatus(40L);
            bo.setFinishTime(date);
        }


        return toAjax(iApiOrderService.updateByBo(bo));
    }

    /**
     * 删除订单
     *
     * @param orderIds 主键串
     */
    @SaCheckPermission("service:apiorder:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] orderIds) {
        return toAjax(iApiOrderService.deleteWithValidByIds(Arrays.asList(orderIds), true));
    }
}
